import {
    UserLogin,
    UserRegister,
    SendUserCode,
    UserLoginByCode,
    SetOnline,
    SetTaskScore,
} from "~/api";
import { connectSocket } from "~/utils/socket";
import { aesEncrypt } from "~/utils/encrypt";
import timeExit from "~/utils/timeExit";

let codeMaxSecond = 0;
let codeInterval = null;

const infoVerify = ({ phone, type, code, password, birthday }) => {
    if (isEmpty(phone)) {
        Message().warning("请输入手机号");
        return false;
    }

    if (!isPhone(phone)) {
        Message().warning("请输入正确的手机号");
        return false;
    }

    if (type == 3 && isEmpty(code)) {
        Message().warning("请输入验证码");
        return false;
    }

    if (isEmpty(password)) {
        Message().warning("请输入密码");
        return false;
    }

    if (password.length < 6 || password.length > 16) {
        Message().warning("请输入6到16位密码");
        return false;
    }

    if (type == 3 && birthday == "") {
        Message().warning("请选择出生日期");
        return false;
    }

    // if (
    //     type == 3 &&
    //     !/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,20}$/.test(
    //         password
    //     )
    // ) {
    //     Message().warning("密码需要包含大小写字母、数字、特殊字符");
    //     return false;
    // }

    return true;
};

export const useContent = () => {
    const userStore = useUserStore();
    const pageStore = usePageStore();
    const route = useRoute();
    const type = ref(1); // 1: 登录 2: 验证码登录 3: 注册
    const num = ref(86);
    const phone = ref(userStore.loginInfo.phone || "");
    const password = ref(userStore.loginInfo.password || "");
    const codeText = ref("获取验证码");
    const code = ref("");
    const birthday = ref("");
    const rememberPassword = ref(Object.keys(userStore.loginInfo).length !== 0);
    const experience_code = ref("");
    let redirect = route.query.redirect;

    const modalTitle = computed(
        () => ({ 1: "密码登录", 2: "欢迎登录", 3: "账号注册" }[type.value])
    );

    const LoginSuccess = async (res, callback) => {
        if (res.code == 200) {
            try {
                Message().success("登录成功");
                userStore.token = res.data.token;

                await GET_USERINFO();
                await GET_AVATAR();
                await GET_MIDNUM();

                if (process.env.NODE_ENV === "production") {
                    SetOnline();
                    timeExit();
                }
                HAS_NEW_MESSAGE();
                connectSocket();
                NoticeTips();

                if (route.query.opencode) {
                    opener.postMessage({ token: res.data.token, code: route.query.opencode }, "*");

                    setTimeout(() => {
                        window.close();
                    }, 2000);

                    return;
                }

                if (redirect) {
                    if (redirect.includes("http")) {
                        window.location.replace(
                            redirect +
                            `${redirect.includes("?") ? "&" : "?"}ticket=` +
                            res.data.token
                        );
                    } else {
                        navigateTo(redirect, { replace: true });
                    }
                } else {
                    // 积分处理
                    if (
                        pageStore.scoreParams &&
                        JSON.stringify(pageStore.scoreParams) !== "{}"
                    ) {
                        SetTaskScore({
                            code: pageStore.scoreParams.code,
                            _id: pageStore.scoreParams._id,
                        });
                        pageStore.scoreParams = {};
                    }
                    // 跳转处理
                    if (
                        pageStore.urlParams &&
                        JSON.stringify(pageStore.urlParams) !== "{}"
                    ) {
                        let url = pageStore.urlParams.url;
                        let search = pageStore.urlParams.search || "";
                        if (pageStore.urlParams.params) {
                            if (pageStore.urlParams.params.includes("uid")) {
                                search +=
                                    (search ? "&" : "") + "uid=" + res.data.id;
                            }
                        }

                        if (pageStore.urlParams.encrypt && search) {
                            search = aesEncrypt(search);
                        }

                        if (pageStore.isLoginOpen) {
                            navigateTo(url + (search ? "?" + search : ""), {
                                external: url.includes("http"),
                                replace: true,
                                open: true,
                            });

                            if (!pageStore.isMobile) {
                                navigateTo(pageStore.loginBackUrl);
                            }
                        } else {
                            navigateTo(url + (search ? "?" + search : ""), {
                                external: url.includes("http"),
                                replace: true,
                            });
                        }

                        if (!pageStore.isMobile) {
                            navigateTo(pageStore.loginBackUrl || "/", {
                                replace: true,
                            });
                        }
                    } else {
                        navigateTo(pageStore.loginBackUrl || "/", {
                            replace: true,
                        });
                    }
                }
                typeof callback === "function" && callback(res);
            } catch (err) {
                alert(err);
            }
        } else {
            Message().error(res.msg);
        }
    };

    const onSendCodeSuccess = () => {
        const _func = () => {
            if (codeMaxSecond === 0) {
                codeText.value = "获取验证码";
                clearInterval(codeInterval);
            } else {
                codeText.value = `${codeMaxSecond--}s`;
            }
        };
        codeMaxSecond = 120;
        codeInterval = setInterval(_func, 1000);
        _func();
    };

    const onSendCode = async () => {
        if (codeMaxSecond > 0) return;
        if (isPhone(phone.value)) {
            const res = await SendUserCode({
                phone: phone.value,
                event: {
                    2: "login",
                    3: "register",
                }[type.value],
            });

            if (res.code == 200) {
                Message().success("发送成功");
                onSendCodeSuccess();
            } else {
                Message().error(res.msg);
            }
        } else {
            Message().warning("请输入正确的手机号");
        }
    };

    const onPwdLogin = async () => {
        const verify = infoVerify({
            phone: phone.value,
            type: type.value,
            code: code.value,
            password: password.value,
        });

        if (verify) {
            const res = await UserLogin({
                username: phone.value,
                password: password.value,
            });

            LoginSuccess(res, () => {
                if (rememberPassword.value) {
                    userStore.SET_LOGININFO({
                        phone: phone.value,
                        password: password.value,
                    });
                } else {
                    userStore.SET_LOGININFO({});
                }
            });
        }
    };

    const onCodeLogin = async () => {
        if (isEmpty(phone.value)) {
            Message().warning("请输入手机号");
            return false;
        }

        if (!isPhone(phone.value)) {
            Message().warning("请输入正确的手机号");
            return false;
        }

        if (isEmpty(code.value)) {
            Message().warning("请输入验证码");
            return false;
        }

        const res = await UserLoginByCode({
            mobile: phone.value,
            code: code.value,
        });

        LoginSuccess(res);
    };

    const onChangeType = (val) => (type.value = val);

    const onForgetPwd = () => navigateTo("/forgetPwd");

    const toRegister = () => navigateTo("/register.html");

    const onRegister = async () => {
        const verify = infoVerify({
            phone: phone.value,
            type: type.value,
            code: code.value,
            password: password.value,
            birthday: birthday.value,
        });

        if (verify) {
            const res = await UserRegister({
                phone: phone.value,
                password: password.value,
                code: code.value,
                experience_code: experience_code.value,
                birthday: birthday.value,
            });

            if (res.code == 200) {
                Message().success("注册成功");
                type.value = 1;
            } else {
                Message().error(res.msg);
            }
        }
    };

    const onSubmit = () => {
        switch (type.value) {
            case 1:
                onPwdLogin();
                break;
            case 2:
                onCodeLogin();
                break;
            case 3:
                onRegister();
                break;
            default:
                break;
        }
    };

    const birthdayDisabled = (date) => {
        return date > new Date();
    };

    return {
        type,
        num,
        birthday,
        phone,
        password,
        codeText,
        code,
        rememberPassword,
        experience_code,
        modalTitle,
        birthdayDisabled,
        onSendCode,
        onChangeType,
        onPwdLogin,
        onForgetPwd,
        onSubmit,
        toRegister
    };
};
